package com.example.demo.controller;
import com.example.demo.entity.ResponseUtil;
import com.example.demo.entity.User;
import com.example.demo.service.SpringbootService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
//@EnableGlobalMethodSecurity(prePostEnabled = true)//只有ADMIN 的角色才能访问
public class SpringbootController {

    @Autowired
    private SpringbootService userService;

    @RequestMapping(value="/spring-test",produces="application/json;charset=UTF-8")
    @ResponseBody
    // 指定该接口只能被ADMIN角色的用户访问，ROLE_这个前缀是固定要写的
    //@PreAuthorize("hasAuthority('R_ADMIN')")
    public ResponseUtil test(int page , int limit){
        List<User> list = userService.selectAll((page-1)*limit,limit);
        ResponseUtil r = new ResponseUtil(0,"成功",userService.count() , list);
        //r.setData(userService.selectAll());
        return r;
    }

    @RequestMapping(value="/Tableupdate",produces="application/json;charset=UTF-8")
    @ResponseBody
    public int test(@RequestBody User user){
        int n = userService.update(user);
        return n;
    }

    @RequestMapping(value = "/index",produces="application/json;charset=UTF-8")
    public String test3()
    {
        return "index";
    }

    /**
     * 登录异常处理 - 前后端一体的情况下
     * @param request
     * @param response
     */
    @RequestMapping("/login/error")
    public void loginError(HttpServletRequest request, HttpServletResponse response) {
        AuthenticationException e = (AuthenticationException) request.getSession().getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
        System.out.println(e.getMessage());
    }

    @RequestMapping(value="/logins",produces="application/json;charset=UTF-8")
    @ResponseBody
    //@PreAuthorize("hasAuthority('R_HELLO')")
    public String login(@RequestParam(name = "uid",defaultValue = "2625")int id ){

       // return userService.selectOne(id);
        String username1= SecurityContextHolder.getContext().getAuthentication().getName();
        return  username1;
    }
}
